#include "dataquerypage.h"
#include "ui_dataquerypage.h"
#include "qtableview.h"
#include "QDate"
#include "Config/constant.h"
#include "DBOperation/mysql.h"
#include "Report/printreport.h"
#include "dialog/myhelper.h"
#include "Report/login.h"
#include "QPrinter"
#include "QPainter"
#include "Report/appgreport.h"
#include "Report/anf.h"
#include "Report/hrv.h"
DataQueryPage::DataQueryPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DataQueryPage)
{
    ui->setupUi(this);
    setBg();
    if(Constant::ShowFullScreen)
        this->showFullScreen();

    initTableView();
    ui->pushButton_Delete->setEnabled(false);
    ui->lineEdit_Content->setText("");

    QueryDataBase();
    mrp=new MeasureResultPage();
    connect(this,SIGNAL(SendUserInfoToResult(UserInfoBeab)),mrp,SLOT(getUserInfoFromMeasure(UserInfoBeab)));
    mrp->hide();
    ui->dateEdit->setCalendarPopup(true); //设置日历弹出
    ui->dateEdit->setDate(QDate::currentDate());
    ui->dateEdit->setDisplayFormat("yyyy年MM月dd日");

    ui->dateEdit_2->setCalendarPopup(true); //设置日历弹出
    ui->dateEdit_2->setDate(QDate::currentDate());
    ui->dateEdit_2->setDisplayFormat("yyyy年MM月dd日");
    m_nCheckedCount=0;
    QSettings *setting=new QSettings("./Configuration.ini",QSettings::IniFormat);
    setting->beginGroup("Config");
    printType=setting->value("PrintType").toString();
    setting->endGroup();
    delete setting;
}
/**
 * 功能：设置背景图片
 * @brief SettingPage::setBg
 */
void DataQueryPage::setBg()
{
    QPalette pal = this->palette();
    pal.setBrush(QPalette::Window,QBrush(QPixmap(":/images/MeasurePage/measure_bg.png")));
    setPalette(pal);
}
DataQueryPage::~DataQueryPage()
{
    delete mrp;
    delete ui;
}
void DataQueryPage::QueryDataBase()
{
    QString Content=ui->lineEdit_Content->text();
    QString time1=getTime(ui->dateEdit);
    QString time2=getTime(ui->dateEdit_2);
    m_dataInfoTableHash.clear();
    QString file=Constant::DataBasePath;
    MySql *mySql = new MySql(file);
    dibs=mySql->DataQueryBy(Content,time1,time2);

    int dataLen=dibs.size();
    if(dataLen>0)
    {
        for(int i=0;i<dataLen;i++)
        {
            DATAINFO_TABLE_DATA data;
            data.UserID=dibs.at(i).UserID;
            data.UserName=dibs.at(i).UserName;
            data.UserAge=dibs.at(i).UserAge;
            data.UserSex=dibs.at(i).UserSex;
            data.UserHeight=dibs.at(i).UserHeight;
            data.UserWeight=dibs.at(i).UserWeight;
            data.MeasureTime=dibs.at(i).MeasureTime;
            data.dibs=dibs.at(i);
            m_dataInfoTableHash.insert(data.MeasureTime,data);
        }
        RefreshTable();
    }
    delete mySql;
}
QString DataQueryPage::getTime(QDateEdit *de)
{
    QDate cdate = de->date();
    QString year=cdate.toString("yyyy");
    QString month=cdate.toString("MM");
    if(month.size()==1)
        month="0"+month;
    QString day=cdate.toString("dd");
    if(day.size()==1)
        day="0"+day;
    QString time=year+"-"+month+"-"+day;
    return time;
}
void DataQueryPage::on_pushButton_Query_clicked()
{
    QString Content=ui->lineEdit_Content->text();
    QString time1=getTime(ui->dateEdit);
    QString time2=getTime(ui->dateEdit_2);
    m_dataInfoTableHash.clear();
    QString file=Constant::DataBasePath;
    MySql *mySql = new MySql(file);
    dibs=mySql->DataQueryBy(Content,time1,time2);

    int dataLen=dibs.size();
    qDebug()<<"dataLen="<<dataLen;
    if(dataLen>0)
    {
        for(int i=0;i<dataLen;i++)
        {
            DATAINFO_TABLE_DATA data;
            data.UserID=dibs.at(i).UserID;
            data.UserName=dibs.at(i).UserName;
            data.UserAge=dibs.at(i).UserAge;
            data.UserSex=dibs.at(i).UserSex;
            qDebug()<<"UserSex="<<dibs.at(i).UserSex;
            data.UserHeight=dibs.at(i).UserHeight;
            data.UserWeight=dibs.at(i).UserWeight;
            data.MeasureTime=dibs.at(i).MeasureTime;
            data.dibs=dibs.at(i);
            m_dataInfoTableHash.insert(data.MeasureTime,data);
        }

    }
    RefreshTable();
}

void DataQueryPage::initTableView()
{
    //自定义表头操作
//    m_pTableHeader = new QHeaderView(Qt::Horizontal, this);//表头
//    m_pTableHeader->setStretchLastSection(true);//表头最后一列填充
//    ui->tableView->setHorizontalHeader(m_pTableHeader);//设置表头
    ui->tableView->verticalHeader()->setFont(QFont( "黑体", 22, QFont::Black ));


    //创建model（目前使用的是标准数据模型，可以自定义数据模型），绑定model
    m_pTableModel = new QStandardItemModel(this);
    ui->tableView->setModel(m_pTableModel);//设置model
    ui->tableView->verticalHeader()->hide();


    //创建表头信息
    QStringList headerList;
    headerList << "选中" << tr("编号")   << tr("姓名")<< tr("年龄") << tr("性别") << tr("身高") << tr("体重")<< tr("测量时间");
    m_pTableModel->setHorizontalHeaderLabels(headerList);


    //单击
    connect(ui->tableView, &QTableView::clicked,this, &DataQueryPage::on_tableViewClick);
    //双击
    connect(ui->tableView, &QTableView::doubleClicked,this, &DataQueryPage::on_tableViewDbClick);

    //标题头排序
    connect(ui->tableView->horizontalHeader(), &QHeaderView::sectionClicked,this, &DataQueryPage::on_tableViewSort);
    //全选
//    connect(m_pTableHeader, &QHeaderView::stateChanged,this, &DataQueryPage::on_tableViewSelectAllCheckBoxClick);

    //设置列宽
    setColumnWidth();

}
/*************************
 * QTableView-单击事件
 * ***********************/
void DataQueryPage::on_tableViewClick(QModelIndex nIndex)
{

    qDebug()<<"on_tableViewClick";
    int nRow = nIndex.row();
    int nCol = nIndex.column();

    Qt::CheckState oldState = m_pTableModel->item(nRow, COLUMN_CHECKBOX)->checkState();
    Qt::CheckState newState;

    if(oldState == Qt::Unchecked)
    {
        newState = Qt::Checked;
        m_nCheckedCount++;
    }
    else
    {
        newState = Qt::Unchecked;
        m_nCheckedCount--;
    }
    m_pTableModel->item(nRow, COLUMN_CHECKBOX)->setCheckState(newState);

    if(newState == Qt::Unchecked || m_nCheckedCount == m_pTableModel->rowCount())
    {
//        m_pTableHeader->onStateChanged(newState);//改变标题栏的全选状态
    }
    qDebug()<<"on_tableViewClick"<<m_nCheckedCount;
    if(m_nCheckedCount>0)
        ui->pushButton_Delete->setEnabled(true);
    else
        ui->pushButton_Delete->setEnabled(false);
}

/*************************
 * QTableView-双击事件
 * ***********************/
void DataQueryPage::on_tableViewDbClick(QModelIndex nIndex)
{

    int row = nIndex.row();
    QStandardItem *qdi_Measuretime=m_pTableModel->item(row,COLUMN_MEASURETIME);
    DATAINFO_TABLE_DATA dta=m_dataInfoTableHash.find(qdi_Measuretime->text()).value();

    UserInfoBeab uib;
    uib.UserID=dta.UserID;
    uib.UserName=dta.UserName;
    uib.UserAge=dta.UserAge;
    uib.UserSex=dta.UserSex;
    uib.UserHeight=dta.UserHeight;
    uib.UserWeight=dta.UserWeight;
    uib.MeasureTime=dta.MeasureTime;
    emit SendUserInfoToResult(uib);
    mrp->show();
    qDebug() << "Db Click row:" << row;
}
/*************************
 * QTableView-排序
 * ***********************/
void DataQueryPage::on_tableViewSort(int nColumn)
{

    //点击表头实现排序
    //    ui->tableView->horizontalHeader()->setSortIndicatorShown(true);
    //    ui->tableView->sortByColumn(nColumn,Qt::SortOrder::AscendingOrder);
}
/*************************
 * QTableView-响应表头全选操作
 * ***********************/
void DataQueryPage::on_tableViewSelectAllCheckBoxClick(Qt::CheckState state)
{
    int nRowCount = m_pTableModel->rowCount();//当前行数

    for(int i = 0; i < nRowCount; i++)
    {
        m_pTableModel->item(i, COLUMN_CHECKBOX)->setCheckState(state);
    }
}

/*************************
 * QTableView-设置列宽
 * ***********************/
void DataQueryPage::setColumnWidth()
{
    //1358
    ui->tableView->setColumnWidth(COLUMN_CHECKBOX,100);
    ui->tableView->setColumnWidth(COLUMN_ID, 300);
    ui->tableView->setColumnWidth(COLUMN_Name, 300);
    ui->tableView->setColumnWidth(COLUMN_Age, 60);
    ui->tableView->setColumnWidth(COLUMN_Sex, 60);
    ui->tableView->setColumnWidth(COLUMN_Height,60);
    ui->tableView->setColumnWidth(COLUMN_Weight,60);
    ui->tableView->setColumnWidth(COLUMN_MEASURETIME, 418);
    ui->tableView->horizontalHeader()->setStretchLastSection(true);

}

void DataQueryPage::RefreshTable()
{
    if(m_pTableModel->rowCount() > 0)
    {
        m_pTableModel->removeRows(0, m_pTableModel->rowCount());
    }
    QHashDataInfoTableIterator i = m_dataInfoTableHash.begin();
    int row = 0;
    for(; i != m_dataInfoTableHash.end(); ++i)
    {
        DATAINFO_TABLE_DATA data = i.value();
        //可以通过insertRow和setData增加数据
        m_pTableModel->insertRow(row, QModelIndex());
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_CHECKBOX), "");
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_ID), data.UserID);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_Name), data.UserName);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_Age), data.UserAge);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_Sex), data.UserSex);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_Height), data.UserHeight);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_Weight), data.UserWeight);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_MEASURETIME), data.MeasureTime);

        //也可以通过setItem增加数据
        //m_pTableModel->setItem(row, COLUMN_CHECKBOX, new QStandardItem(""));

        // 设置全部列居中显示
        for(int j = COLUMN_CHECKBOX; j <= COLUMN_MEASURETIME; j++)
        {
            m_pTableModel->item(row, j)->setTextAlignment(Qt::AlignCenter);
        }
        row++;
    }
}

void DataQueryPage::on_bt_return_clicked()
{
    this->close();
}


void DataQueryPage::on_pushButton_Print_clicked()
{
    QString file=Constant::DataBasePath;
    MySql *mySql = new MySql(file);

    QHashDataInfoTableIterator i = m_dataInfoTableHash.begin();
    int row = 0;
    for(; i != m_dataInfoTableHash.end(); ++i)
    {
        DATAINFO_TABLE_DATA data = i.value();
        if(m_pTableModel->item(row,0)->checkState()==Qt::Checked)
        {
            QString userMeasuretime=m_pTableModel->item(row,COLUMN_MEASURETIME)->text();
            DataBeans dbs=mySql->DataQueryByMeasureTime(userMeasuretime);
            if(Constant::ReportType==2){
                PrintReport pr;//
                pr.Report_HRV_Professional(dbs);
                pr.Report_APPG_Professional(dbs);
            }
            if(Constant::ReportType==3)
            {

                QPrinter printer,printer2;
                printer.setPageSize(QPageSize::A4);
                printer2.setPageSize(QPageSize::A4);
                //输出文件到d盘data文件夹
                if(printType=="输出pdf"){
                    QString ParentFolder="D:\\data\\"+dbs.UserID;
                    QDir dir(ParentFolder);
                    QString fileName;
                    if(dir.exists())
                    {
                        fileName=ParentFolder+"\\"+dbs.MeasureTime.replace(":","")+".pdf";
                    }else
                    {
                        bool ok = dir.mkpath(ParentFolder);//创建多级目录
                        if(ok)
                        {
                            fileName=ParentFolder+"\\"+dbs.MeasureTime.replace(":","")+".pdf";
                        }
                    }
                    printer.setOutputFileName(fileName);

                    printer.setResolution(300);//值越大分辨率越高
                    printer.setPageMargins(QMarginsF(0, 0, 0, 0));
                    Login report1;
                    HRV report2;
                    Anf report3;
                    APPGReport report4;
                    report1.setValue(dbs);
                    report2.setValue(dbs);
                    report3.setValue(dbs);
                    report4.setValue(dbs);

                    QPixmap pixmap1=report1.grab(report1.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPixmap pixmap2=report2.grab(report2.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPixmap pixmap3=report3.grab(report3.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPixmap pixmap4=report4.grab(report4.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPainter painter;
                    painter.begin(&printer);
                    painter.drawPixmap(0,0,pixmap1); //按照坐标画图
                    printer.newPage();
                    painter.drawPixmap(0,0,pixmap2); //按照坐标画图
                    printer.newPage();
                    painter.drawPixmap(0,0,pixmap3); //按照坐标画图
                    printer.newPage();
                    painter.drawPixmap(0,0,pixmap4); //按照坐标画图
                    painter.end();
                    myHelper::ShowMessageBoxInfo("导出完毕！");

                }else if(printType=="打印机打印")
                {
                    printer.setResolution(300);//值越大分辨率越高
                    printer.setPageMargins(QMarginsF(0, 0, 0, 0));
                    Login report1;
                    HRV report2;
                    Anf report3;
                    APPGReport report4;
                    report1.setValue(dbs);
                    report2.setValue(dbs);
                    report3.setValue(dbs);
                    report4.setValue(dbs);

                    QPixmap pixmap1=report1.grab(report1.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPixmap pixmap2=report2.grab(report2.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPixmap pixmap3=report3.grab(report3.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPixmap pixmap4=report4.grab(report4.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPainter painter;
                    painter.begin(&printer);
                    painter.drawPixmap(0,0,pixmap1); //按照坐标画图
                    printer.newPage();
                    painter.drawPixmap(0,0,pixmap2); //按照坐标画图
                    printer.newPage();
                    painter.drawPixmap(0,0,pixmap3); //按照坐标画图
                    printer.newPage();
                    painter.drawPixmap(0,0,pixmap4); //按照坐标画图
                    painter.end();
                }else if(printType=="输出pdf并打印")
                {
                    QString ParentFolder="D:\\data\\"+dbs.UserID;
                    QDir dir(ParentFolder);
                    QString fileName;
                    if(dir.exists())
                    {
                        fileName=ParentFolder+"\\"+dbs.MeasureTime.replace(":","")+".pdf";
                    }else
                    {
                        bool ok = dir.mkpath(ParentFolder);//创建多级目录
                        if(ok)
                        {
                            fileName=ParentFolder+"\\"+dbs.MeasureTime.replace(":","")+".pdf";
                        }
                    }
                    printer.setOutputFileName(fileName);

                    printer.setResolution(300);//值越大分辨率越高
                    printer.setPageMargins(QMarginsF(0, 0, 0, 0));

                    printer2.setResolution(300);//值越大分辨率越高
                    printer2.setPageMargins(QMarginsF(0, 0, 0, 0));
                    Login report1;
                    HRV report2;
                    Anf report3;
                    APPGReport report4;
                    report1.setValue(dbs);
                    report2.setValue(dbs);
                    report3.setValue(dbs);
                    report4.setValue(dbs);

                    QPixmap pixmap1=report1.grab(report1.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPixmap pixmap2=report2.grab(report2.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPixmap pixmap3=report3.grab(report3.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPixmap pixmap4=report4.grab(report4.rect()); //抓取界面widget区域，可以抓取任意控件区域
                    QPainter painter;
                    painter.begin(&printer);
                    painter.drawPixmap(0,0,pixmap1); //按照坐标画图
                    printer.newPage();
                    painter.drawPixmap(0,0,pixmap2); //按照坐标画图
                    printer.newPage();
                    painter.drawPixmap(0,0,pixmap3); //按照坐标画图
                    printer.newPage();
                    painter.drawPixmap(0,0,pixmap4); //按照坐标画图
                    painter.end();

                    painter.begin(&printer2);
                    painter.drawPixmap(0,0,pixmap1); //按照坐标画图
                    printer2.newPage();
                    painter.drawPixmap(0,0,pixmap2); //按照坐标画图
                    printer2.newPage();
                    painter.drawPixmap(0,0,pixmap3); //按照坐标画图
                    printer2.newPage();
                    painter.drawPixmap(0,0,pixmap4); //按照坐标画图
                    painter.end();
                    myHelper::ShowMessageBoxInfo("导出完毕！");

                }


            }
        }
        row++;
    }

    delete mySql;


}


void DataQueryPage::on_pushButton_Delete_clicked()
{
    if(myHelper::ShowMessageBoxQuesion("您确认要删除所选项目吗？")==1)
    {
        QString file=Constant::DataBasePath;
        MySql *mySql = new MySql(file);
        PrintReport pr;
        QHashDataInfoTableIterator i = m_dataInfoTableHash.begin();
        int row = 0;
        for(; i != m_dataInfoTableHash.end(); ++i)
        {
            DATAINFO_TABLE_DATA data = i.value();
            if(m_pTableModel->item(row,0)->checkState()==Qt::Checked)
            {
                QString userMeasuretime=m_pTableModel->item(row,COLUMN_MEASURETIME)->text();
                mySql->MyDataDelete(userMeasuretime);
            }
            row++;
        }
        delete mySql;
        on_pushButton_Query_clicked();
    }

}

